package com.ucode.wap.hrm.controller;

import cn.hutool.core.util.ArrayUtil;
import cn.hutool.core.util.ObjUtil;
import com.ucode.hrm.service.HrmAttendanceConfigService;
import com.ucode.hrm.service.HrmAttendanceRecordService;
import com.ucode.hrm.service.HrmAttendanceStatisticsService;
import com.ucode.model.hrm.HrmAttendanceConfig;
import com.ucode.model.hrm.HrmAttendanceRecord;
import com.ucode.model.hrm.HrmEmployee;
import com.ucode.model.hrm.convert.HrmAttendanceRecordConvert;
import com.ucode.model.hrm.enums.HrmClockType;
import com.ucode.model.hrm.form.HrmAttendanceRecordCreateForm;
import com.ucode.model.hrm.vo.HrmAttendanceMonthlyStatsVO;
import com.ucode.model.hrm.vo.HrmAttendanceRecordVO;
import com.ucode.tool.annotation.NeedLogin;
import com.ucode.tool.base.ResponseResult;
import com.ucode.tool.base.enums.GlobalResultCodeEnum;
import com.ucode.tool.exception.UcodeServiceException;
import com.ucode.wap.base.core.CurrentLoginUserHandler;
import com.ucode.wap.hrm.service.ApiHrmEmployeeService;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.media.Schema;
import io.swagger.v3.oas.annotations.tags.Tag;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import javax.validation.Valid;
import java.time.LocalDate;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Tag(name = "移动端 - 人力资源系统 - 打卡记录")
@RestController
@RequestMapping("/hrm/attendance-record")
@Validated
public class ApiHrmAttendanceRecordController {
    @Resource
    private HrmAttendanceRecordService hrmAttendanceRecordService;
    @Resource
    private ApiHrmEmployeeService apiHrmEmployeeService;
    @Resource
    private CurrentLoginUserHandler currentLoginUserHandler;
    @Resource
    private HrmAttendanceConfigService hrmAttendanceConfigService;
    @Resource
    private HrmAttendanceStatisticsService hrmAttendanceStatisticsService;

    @NeedLogin
    @GetMapping("/list")
    @Operation(summary = "获得列表")
    public ResponseResult<List<HrmAttendanceRecord>> list(
            @Schema(description = "创建时间区间",example = "2022-07-01,2022-07-31")  @RequestParam(value = "workDateInterval",required = false) LocalDate[] workDateInterval){

        Map<String,Object> condition = new HashMap<>();


        if(ArrayUtil.isNotEmpty(workDateInterval) && workDateInterval.length == 2){
            condition.put("startTime",workDateInterval[0]);
            condition.put("endTime",workDateInterval[1]);
        }

        HrmEmployee employee = apiHrmEmployeeService.verifyCurrentUserBindAndGetEmployee();
        condition.put("employeeId",employee.getId());
        condition.put("deltag",false);

        // 查询打卡记录
        List<HrmAttendanceRecord> list = hrmAttendanceRecordService.queryObjectForList(condition,0);

        return ResponseResult.success(list);
    }

    @NeedLogin
    @GetMapping("/monthly-stats")
    @Operation(summary = "月度考勤统计")
    public ResponseResult<HrmAttendanceMonthlyStatsVO> getMonthlyStats(
            @Schema(description = "统计月度，yyyy-MM格式",example = "2022-07")  @RequestParam(value = "month",required = true) String month){

        HrmEmployee employee = apiHrmEmployeeService.verifyCurrentUserBindAndGetEmployee();
        HrmAttendanceMonthlyStatsVO bean = hrmAttendanceStatisticsService.getMonthlyStats(employee.getId(),month);
        return ResponseResult.success(bean);
    }

    @NeedLogin(validate = true)
    @GetMapping("/get-config")
    @Operation(summary = "获取打卡配置")
    public ResponseResult<HrmAttendanceConfig> getConfig() {
        HrmEmployee employee = apiHrmEmployeeService.verifyCurrentUserBindAndGetEmployee();
        HrmAttendanceConfig hrmAttendanceConfig = hrmAttendanceConfigService.validate(employee.getAttCfgId());
        return ResponseResult.success(hrmAttendanceConfig);
    }

    @NeedLogin(validate = true)
    @PostMapping("/submit")
    @Operation(summary = "提交打卡")
    public ResponseResult<HrmAttendanceRecordVO> submit(@Valid @RequestBody HrmAttendanceRecordCreateForm form) {
        HrmAttendanceRecord bean = HrmAttendanceRecordConvert.INSTANCE.convert(form);
        HrmEmployee employee = apiHrmEmployeeService.verifyCurrentUserBindAndGetEmployee();

        if(ObjUtil.isNull(employee.getAttCfgId()) || ObjUtil.equals(employee.getAttCfgId(), 0)){
            throw new UcodeServiceException(GlobalResultCodeEnum.VALIDATE_FAILED.getCode(), "员工未设置考勤配置");
        }

        HrmAttendanceConfig hrmAttendanceConfig = hrmAttendanceConfigService.validate(employee.getAttCfgId());
        HrmClockType clockType = HrmClockType.valueOf(form.getClockType());
        if(ObjUtil.isNull(clockType))
            throw new UcodeServiceException(GlobalResultCodeEnum.VALIDATE_FAILED.getCode(), "打卡类型错误");


        //这里需要增加一个锁象，防止员工快速提交 TODO 待实现

        hrmAttendanceRecordService.processAttendance(hrmAttendanceConfig, employee.getId(), employee.getCompanyId(), employee.getProjectId(),form.getWorkDate(), clockType, form.getLat(), form.getLng(), form.getLocation(), form.getImages(), form.getRemark());
        return ResponseResult.success();
    }

}
